#include <iostream>
using std::cout;
using std::endl;

class Data
{
public:
    Data(){
        /* cout << "Data()" << endl; */
    }
    ~Data(){
        /* cout << "~Data()" << endl; */
    }

    int getData() const{ return _data; }
private:
    int _data = 10;
};

class MiddleLayer
{
public:
    MiddleLayer(Data * p)
    : _pdata(p)
    {
        /* cout << "MiddleLayer(Data*)" << endl; */
    }

    ~MiddleLayer(){
        /* cout << "~MiddleLayer()" << endl; */
        if(_pdata){
            delete _pdata;
            _pdata = nullptr;
        }
    }

    Data * operator->(){
        return _pdata;
    }

    Data & operator*(){
        return *_pdata;
    }
private:
    Data * _pdata;
};

void test0(){
    Data * p1 = new Data();
    cout << p1->getData() << endl;

    MiddleLayer ml(p1);
    /* delete p1; */
}

void test1(){
    Data * p1 = new Data();
    cout << p1->getData() << endl;
    cout << (*p1).getData() << endl;
    delete p1;

    //智能指针的雏形
    //利用局部对象的生命周期来回收其托管的资源
    //ml是一个对象，但完全可以像原生的Data*一样使用
    //同时，在ml对象销毁还可以对堆空间资源进行自动回收
    MiddleLayer ml(new Data());
    cout << ml->getData() << endl;
    /* cout << (ml.operator->())->getData() << endl;//本质 */
    cout << (*ml).getData() << endl;
    /* cout << (ml.operator*()).getData() << endl;//本质 */


}

int main(void){
    test1();
    return 0;
}
